package com.guigu.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.erp.dto.StoragePayDetailsDto;
import com.guigu.erp.mapper.StoragePayDetailsMapper;
import com.guigu.erp.pojo.StorageCell;
import com.guigu.erp.pojo.StoragePay;
import com.guigu.erp.pojo.StoragePayDetails;
import com.guigu.erp.service.StorageCellService;
import com.guigu.erp.service.StoragePayDetailsService;
import com.guigu.erp.service.StoragePayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class StoragePayDetailsServiceImpl extends ServiceImpl<StoragePayDetailsMapper, StoragePayDetails>
    implements StoragePayDetailsService {

    @Autowired
    private StoragePayService storagePayService;

    @Autowired
    private StoragePayDetailsService storagePayDetailsService;

    @Autowired
    private StorageCellService storageCellService;


    @Override
    @Transactional
    public boolean ModifyTheOutboundDetails(StoragePayDetailsDto dto) {
        //1.修改出库明细的调度标志 确认出库件数
        dto.setPayTag("K002-2");
        storagePayDetailsService.updateById(dto);
        //查询所有出库单的明细
        QueryWrapper<StoragePay> wrapper = new QueryWrapper<>();
        wrapper.eq("PAY_ID",dto.getPayId());
        StoragePay pay = storagePayService.getOne(wrapper);

        QueryWrapper<StoragePayDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PARENT_ID",pay.getId());
        queryWrapper.eq("PAY_TAG","K002-1");
        List<StoragePayDetails> list = storagePayDetailsService.list(queryWrapper);

        //2.修改出库单表（明细全部调度完成） 调度标志 确认出库总件数
        //判断是否调度完
        if(list.size()==0){
            //修改调度标志
            pay.setStoreTag("K002-2");
            //修改应出库数量
            pay.setPaidAmountSum(pay.getAmountSum());
            storagePayService.updateById(pay);
        }

        //3.修改库存表的数量
        QueryWrapper<StorageCell> cellQueryWrapper = new QueryWrapper<>();
        cellQueryWrapper.eq("PRODUCT_ID", dto.getProductId());
        StorageCell cellServiceOne = storageCellService.getOne(cellQueryWrapper);
        cellServiceOne.setAmount(cellServiceOne.getAmount().subtract(dto.getPaidAmount()));
        boolean flag = storageCellService.updateById(cellServiceOne);

        return flag;
    }
}
